//
//  UIViewController+ICENoneData.m
//  DemoProduct
//
//  Created by ttouch on 16/1/25.
//  Copyright © 2016年 iCE. All rights reserved.
//

#import "UIViewController+Utils.h"


@implementation UIViewController (Utils)

/// 缩放图片
- (UIImage *)scaleFromImage:(UIImage *)image toSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

/// 获取当前正在显示的ViewController
+ (UIViewController *)currentViewController {
    UIViewController *rootVc = [UIApplication sharedApplication].delegate.window.rootViewController;
    return [rootVc findBestViewController:rootVc];
}

/// 获取当前正在显示的ViewController
- (UIViewController *)currentViewController {
    UIViewController *rootVc = [UIApplication sharedApplication].delegate.window.rootViewController;
    return [self findBestViewController:rootVc];
}

- (UIViewController *)findBestViewController:(UIViewController *)vc {
    if (vc.presentedViewController) {
        // Return presented view controller
        return [self findBestViewController:vc.presentedViewController];
    } else if ([vc isKindOfClass:[UISplitViewController class]]) {
        // Return right hand side
        UISplitViewController *svc = (UISplitViewController *)vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.viewControllers.lastObject];
        else
            return vc;
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        // Return top view
        UINavigationController *svc = (UINavigationController *)vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.topViewController];
        else
            return vc;
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        // Return visible view
        UITabBarController *svc = (UITabBarController *)vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.selectedViewController];
        else
            return vc;
    } else {
        // Unknown view controller type, return last child view controller
        return vc;
    }
}

@end
